import pymysql
from models.configration import DB_CONFIG


def connect_db():
    db_connection= None
    try:
        db_connection = pymysql.connect(**DB_CONFIG)
        print("数据库成功连接")
        with db_connection.cursor() as cursor:
            cursor.execute("SELECT DATABASE();")
            result = cursor.fetchone()
            if result and "DATABASE()" in result:
                db_name = result["DATABASE()"]
                print(f"当前连接的数据库：{db_name}")
            else:
                print("无法获取数据库名称")
        return db_connection
    except Exception as e:
        print(f"数据库错误")
    return None


def connect():
    db = connect_db()
    return db


def close(db_connection):
    if db_connection:
        try:
            db_connection.close()
            print("数据库连接已关闭")
        except Exception as e:
            print(f"关闭数据库连接时出错: {str(e)}")


# 测试数据库连接
# db=connect()
# if db:
#     # 这里可以添加具体的数据库操作
#     with db.cursor() as cursor:
#         cursor.execute(LOGIN,("1","1"))
#         result = cursor.fetchone()
#         print(f"测试查询结果: {result}")
# else:
#     print("无法执行数据库操作，连接失败")
#
# close(db)
